package pers.xiaoliang.concurrency.example;

import pers.xiaoliang.concurrency.annotation.NotThreadSafe;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
* @description: Map计数例子
* @author: xiaoliang.liu
* @date: 2018/7/26 21:43
* @version v1.0
*/
@NotThreadSafe
public class MapExample {

    static HashMap<Integer, Integer> map = new HashMap<>(16);

    /**
     * 线程数量(模拟并发数)
     */
    private static int threadNum = 200;
    /**
     * 请求次数
     */
    private static int clientTotal = 5000;

    private static long count = 0;

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadNum);

        for (int i = 0; i < clientTotal; i++) {
            final int threadNum = i;

            exec.execute(() -> {
                try {
                    semaphore.acquire();
                    func(threadNum);
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        System.out.println(map.size());
    }

    public static void func(int treadNum) {
        map.put(treadNum, threadNum);
    }
}
